package juan.happyge.plugin.myi.service.book.crawler;

import juan.happyge.plugin.myi.config.BookConfig;
import juan.happyge.plugin.myi.config.ConfigManage;
import juan.happyge.plugin.myi.pojo.crawler.CrawlerChapterDetailPojo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.Objects;

/**
 * 总体思路
 * 先下载下来html
 * 解析出需要的文本
 * 解析出下一章的url
 * 加载html
 *
 *
 */
public abstract class AbstractBookCrawler {

    /**
     * 基础配置
     */
    BookConfig bookConfig = ConfigManage.getInstance().getBookConfig();

    /**
     * 分析html界面抽象方法
     * @param document
     * @throws Exception
     */
    public abstract CrawlerChapterDetailPojo analyze(Document document);

    /**
     * 加载html页面
     * @param url
     * @return
     */
    public Document reloadHtml(String url){

        if(StringUtils.isEmpty(url)){
            return null;
        }

        Document document = null;
        try
        {
            document = Jsoup.connect(url).get();
            return document;
        }
        catch (SocketTimeoutException socketTimeoutException){
            System.out.println("请求超时，等待15秒后重新请求");
            try {
                Thread.sleep(15000);
                return reloadHtml(url);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        catch (IOException ioException)
        {
            System.out.println("发生io异常，30秒后重新获取");
            try {
                Thread.sleep(30000);
                return reloadHtml(url);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return document;
    }

    /**
     * 保存章节
     * @throws Exception
     */
    public boolean saveChapter(CrawlerChapterDetailPojo crawlerChapterDetailPojo){

        String bookPath = bookConfig.getBookPath();
        if(StringUtils.isEmpty(bookPath) || Objects.isNull(crawlerChapterDetailPojo)){
            return false;
        }
        try(FileWriter fileWriter = new FileWriter(bookPath, Charset.forName("utf-8"),true)){
            fileWriter.append("\n\n" + crawlerChapterDetailPojo.getTitle() + "\n\n");
            fileWriter.append(crawlerChapterDetailPojo.getContent());
            if(StringUtils.isNotEmpty(crawlerChapterDetailPojo.getNextUrl())){
                fileWriter.append("url=" + crawlerChapterDetailPojo.getNextUrl());
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
